package com.lastproject.ejb.timers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.faces.bean.ManagedProperty;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.lastproject.dto.AnswerDTO;
import com.lastproject.dto.QuestionDTO;
import com.lastproject.dto.QuestionOptionDTO;
import com.lastproject.dto.SurveyDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.AnswerDAORemote;
import com.lastproject.ejb.dao.QuestionDAORemote;
import com.lastproject.ejb.dao.QuestionOptionDAORemote;
import com.lastproject.ejb.dao.SurveyDAORemote;
import com.lastproject.ejb.dao.UserDAORemote;

/**
 * Session Bean implementation class TimerBean
 */
@Stateless
public class TimerBean implements TimerBeanRemote {

	@Resource
	TimerService timerService;

	@ManagedProperty(value = "userDTO")
	UserDTO userDTO;

	@ManagedProperty(value = "surveyDTO")
	SurveyDTO surveyDTO;

	@ManagedProperty(value = "answerDTO")
	AnswerDTO answerDTO;

	@ManagedProperty(value = "questionDTO")
	QuestionDTO questionDTO;

	@ManagedProperty(value = "questionOptionDTO")
	QuestionOptionDTO questionOptionDTO;

	@EJB
	SurveyDAORemote surveyDAORemote;

	@EJB
	UserDAORemote userDAORemote;

	@EJB
	AnswerDAORemote answerDAORemote;

	@EJB
	QuestionDAORemote questionDAORemote;

	@EJB
	QuestionOptionDAORemote questionOptionDAORemote;

	List<UserDTO> users = new ArrayList<UserDTO>();

	List<AnswerDTO> answers = new ArrayList<AnswerDTO>();

	public TimerBean() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void startTimer(Serializable info, long timeInSec) {

		TimerConfig timerConfig = new TimerConfig();
		timerConfig.setInfo(info);
		timerService.createSingleActionTimer(timeInSec, timerConfig);
	}

	public String getUsers(int surveyId) {
		List<AnswerDTO> answersForSurvey = new ArrayList<AnswerDTO>();
		List<UserDTO> users = new ArrayList<UserDTO>();
		List<UserDTO> emailUsers = new ArrayList<UserDTO>();
		String returnUsers = "";

		surveyDTO = surveyDAORemote.getSurveyById(surveyId);

		answers = answerDAORemote.getAll();

		for (AnswerDTO a : answers) {
			int sId = surveyDAORemote.getSurveyById(
					questionDAORemote.findById(
							questionOptionDAORemote.findById(
									a.getIdquestionOption()).getQuestionId())
							.getSurveyId()).getId();

			if (sId == surveyId)
				answersForSurvey.add(a);
		}
		users = surveyDTO.getEmailGroup().getUsers();

		for (UserDTO u : users) {
			boolean isIn = false;
			for (AnswerDTO a : answersForSurvey) {
				if (a.getIdUser() == u.getId())
					isIn = true;
			}
			if (isIn == false)
				emailUsers.add(u);
		}

		returnUsers = returnUsers + emailUsers.size() + "_";
		for (UserDTO u : emailUsers) {
			returnUsers = returnUsers + u.getWorkEmail() + "_";
		}

		return returnUsers;
	}

	@Timeout
	public void sendEmail(Timer t) {

		// send message to MDB
		System.out.println("on timeout");
		InitialContext ic;
		ConnectionFactory cf = null;
		Queue destination = null;
		
		String infoString = t.getInfo().toString();
		String[] tokens = infoString.split("_");
		int idSurvey = Integer.parseInt(tokens[1]);

		try {
			ic = new InitialContext();
			cf = (ConnectionFactory) ic.lookup("jms/firstfactory");
			destination = (Queue) ic.lookup("jms/firstResource");

		} catch (NamingException e) {
			e.printStackTrace();
		}

		// for (int i = 0; i < Integer.parseInt(emails[0]); i++) {
		try (Connection conn = cf.createConnection();
				Session session = conn.createSession(false,
						Session.AUTO_ACKNOWLEDGE);
				MessageProducer producer = session.createProducer(destination)) {
			conn.start();
			Message myMessage = session.createTextMessage();
			myMessage.setStringProperty("emails", getUsers(idSurvey));
			myMessage.setStringProperty("subject",
					"Survey was not completed yet!");
			myMessage.setStringProperty("surveyInfo",
					"Survey " + surveyDTO.getTitle()
							+ " must be completed today!");

			producer.send(myMessage);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		// }

	}

}
